package com.shiroha.video.controller;

import com.mybatisflex.core.paginate.Page;
import com.shiroha.common.utils.PageResult;
import com.shiroha.common.utils.Result;
import com.shiroha.video.pojo.dto.CommentDTO;
import com.shiroha.video.pojo.vo.CommentVO;
import com.shiroha.video.service.ICommentService;
import lombok.AllArgsConstructor;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.JwtClaimAccessor;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;
import java.util.UUID;

@RestController
@RequestMapping("/vs/comments")
@AllArgsConstructor
public class CommentController {

    private final ICommentService commentService;

    // 获取作品评论
    @GetMapping
    public PageResult<CommentVO> getComments(
            @AuthenticationPrincipal Jwt jwt,
            @RequestParam Long workId,
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "30") int pageSize) {
        UUID userId = Optional.ofNullable(jwt)
                .map(JwtClaimAccessor::getSubject)
                .map(UUID::fromString)
                .orElse(null);

        Page<CommentVO> commentVOPage = commentService.selectCommentByPage(userId, workId, pageNum, pageSize);
        return PageResult.<CommentVO>create()
                .setTotal(commentVOPage.getTotalRow())
                .setTotalPage(commentVOPage.getTotalPage())
                .setCurrentPage(pageNum)
                .setPageSize(pageSize)
                .setData(commentVOPage.getRecords());

    }

    // 发布或回复评论
    @PostMapping
    public Result<String> publishComment(@AuthenticationPrincipal Jwt jwt, @RequestBody CommentDTO commentDTO) {
        return commentService.publishComment(UUID.fromString(jwt.getSubject()), commentDTO) ?
                Result.success("发布评论成功") : Result.error("发布评论失败");
    }

    // 删除评论
    @DeleteMapping
    public Result<String> deleteComment(@AuthenticationPrincipal Jwt jwt, @RequestParam Long commentId) {
        return commentService.deleteComment(UUID.fromString(jwt.getSubject()), commentId) ?
                Result.success("删除评论成功") : Result.error("删除评论失败");
    }

    // 置顶评论
    @PutMapping
    public Result<String> pinComment(@AuthenticationPrincipal Jwt jwt, @RequestParam Long commentId) {
        return commentService.pinComment(UUID.fromString(jwt.getSubject()), commentId) ?
                Result.success("置顶成功") : Result.error("置顶失败");
    }
}
